package servlet;

import dao.MusicDao;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/uploadMusicServlet")
@MultipartConfig
public class UploadMusicServlet extends HttpServlet {

    /*private static final String SAVEPATH ="D:\\项目\\Java\\mycloudmusic\\src\\main\\webapp\\music\\";*/
    private static final String SAVEPATH =
            "/home/zhengli/tomcat/apache-tomcat-8.5.69/webapps/mycloudmusic/music/";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        User user = (User) req.getSession().getAttribute("user");
        if(user == null) {
            System.out.println("没有登录，不能上传");
        }else {
            Part part =  req.getPart("filename");
            String header = part.getHeader("Content-Disposition");
            int start = header.lastIndexOf("=");
            String fileName = header.substring(start + 1)
                    .replace("\"", "");

            System.out.println("fileName :" + fileName);


            part.write(SAVEPATH+fileName);

            String singer = req.getParameter("singer");
            System.out.println("歌手："+singer);

            String[] titles = fileName.split("\\.");
            String title = titles[0];

            System.out.println("title:" + title);

            String url = "music\\"+title;
            System.out.println("url："+url);

            SimpleDateFormat sf =
                    new SimpleDateFormat("yyyy-MM-dd");
            String time=sf.format(new Date());

            int userId = user.getId();

            MusicDao musicDao = new MusicDao();
            int ret = musicDao.insert(title,singer,time,url,userId);
            if(ret == 1){
                resp.sendRedirect("list.html");
            }else{
                System.out.println("上传失败！");
                part.delete();
            }
        }
    }
}
